package com.niit.class_3.servlet;

import com.niit.class_3.domain.Users;
import com.niit.class_3.service.IUserService;
import com.niit.class_3.service.impl.UserServiceImpl;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.io.PrintWriter;
import com.google.gson.Gson;

@WebServlet(name = "LoginServlet",value = "/LoginServlet")
public class LoginServlet extends HttpServlet {
    private static final long serialVersionUID = 1L;

    private IUserService us ;

    public LoginServlet() {
        super();
        us = new UserServiceImpl();
    }
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

        //检查session中是否有值
        HttpSession session = request.getSession() ;
        Object user = session.getAttribute("user");
        response.setHeader("Content-Type", "application/json;charset");
        Gson gson = new Gson() ;
        PrintWriter out = response.getWriter() ;
        if(user == null){
            out.append("null");
        }else{
            out.append(gson.toJson(gson));
        }
    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String userName = request.getParameter("username");
        String pwd = request.getParameter("pwd");
        Users user = us.checkUser(userName, pwd);
        if(user != null){
            //登录成功
            HttpSession session = request.getSession();
            session.setAttribute("user", user);
            response.sendRedirect("index.html");
        }else{
            response.sendRedirect("login.html");
        }
    }
}

